<script lang="ts" setup>
import { useVbenModal } from '@vben/common-ui'
import { useI18n } from '@vben/locales'

import { useVbenForm } from '#/adapter/form'
import { fetchUpdatePwd } from '#/api'

import { addEditFormSchema } from './data/AddEditFrom'
import { computed } from 'vue'

defineOptions({
    name: 'FormModelDemo'
})

const { t } = useI18n()

async function onSubmit(values: Record<string, any>) {
    await fetchUpdatePwd({
        newPassword: values.newPassword,
        oldPassword: values.oldPassword
    })
}

const [Form, formApi] = useVbenForm({
    handleSubmit: onSubmit,
    schema: addEditFormSchema,
    showDefaultActions: false
})

const [Modal, modalApi] = useVbenModal({
    fullscreenButton: false,
    onCancel() {
        modalApi.close()
    },
    onConfirm: async () => {
        const ret = await formApi.validate()
        if (ret.valid) {
            formApi.setState({
                submitButtonOptions: { loading: true }
            })
            try {
                await formApi.submitForm()
                modalApi.close()
            } catch {}
            formApi.setState({
                submitButtonOptions: { loading: false }
            })
        }
    },
    onOpenChange(isOpen: boolean) {
        if (isOpen) {
            const { values } = modalApi.getData<Record<string, any>>()
            if (values) {
                formApi.setValues(values)
            }
        }
    },
    title: computed(() => t('EditPassword.editPassword'))
})
</script>
<template>
    <Modal>
        <Form />
    </Modal>
</template>
